package KIT_DB;

sub new 
{
    #   my %config	= Utils->getConfig();

    my $class   		= shift;
    my $db_name		= shift || $Utils::config{'DB_NAME'};
    my $db_storage_type	= shift || "mysql";

    my $self = {
            db_name         => $db_name,
            db_storage_type => $db_storage_type,
    };
    bless $self, 'KIT_DB';
    return $self;
}

sub GetDBHandle
{
    my $self		= shift;
    my $db_name		= shift || $self->{db_name};
    my $db_storage_type	= shift || $self->{db_storage_type};
    
    my $utils   = new Utils();

    my %config	= $utils->get_config();
    my $db_h;
    
    if ($db_storage_type =~ /mysql/)
    {
        my $dsn 	= "DBI:mysql:host=localhost;database=$db_name";
        # print $dsn . " user=" . $config{'DB_USER'} . " pass=" . $config{'DB_PASS'};
        $db_h 	= DBI->connect($dsn, $config{'DB_USER'}, $config{'DB_PASS'}) || die (DBI->errstr());
    }
    else
    {	#	-- Connect to the SQLite database file
        my $conn_string	= "DBI:SQLite:dbname=" . $config{DB_PATH_ABS} . "/$db_name";
        #$Utils::logger->info('Connection string: ', $conn_string);
        $db_h 	= DBI->connect($conn_string) || die "Error opening database " . $! . " \nconn_string = $conn_string";
    }

    return $db_h;
}

sub GetSingleRow
{
    my ($self, $stmt) = @_;

    $Utils::logger->debug($stmt);

    my $db_h	= $self->GetDBHandle($self->{db_name});
    my $hashref	= $db_h->selectrow_hashref($stmt) || die $db_h->errstr() . "\n\n" . $stmt;
    return $hashref;
}

sub GetSingleValue
{
    my ($self, $sql)        = @_;

    my $db_h        = $self->GetDBHandle();
    my $hashref     = $db_h->selectrow_hashref($sql) || die ($db_h->errstr() . "\n\n" . $sql);

    $Utils::logger->debug($sql);

    return $hashref->{ret_val};
}

sub GetMultipleRows
{
    my ($self, $sql)	= @_;

    $Utils::logger->debug($sql);

    my $db_h	= $self->GetDBHandle();
    my $rows	= $db_h->selectall_arrayref($sql) || die ($db_h->errstr . "\n" . $sql . "\n" . $self->{db_name} . "\n");

    return @$rows;
}

sub Insert
{
    my ($self, $sql)	= @_;

    my $db_h	= $self->GetDBHandle();
    # print $sql;
    $db_h->do($sql) || die $db_h->errstr() . "\n\n" . $sql . "\n\n";
    # print $db_h->{'mysql_insertid'}; exit;
    return $db_h->{'mysql_insertid'};
}

sub Update
{
    my ($self, $sql)	= @_;

    my $db_h	= $self->GetDBHandle();
    #  -- fix this to return number of effected records
    return $db_h->do($sql) || die $db_h->errstr() . "\n\n" . $sql;
    # return $ret_val;
}

sub Delete 
{
    my ($self, $sql)    = @_;
    my $db_h	= $self->GetDBHandle();
    #  -- fix this to return number of effected records
    return $db_h->do($sql) || die $db_h->errstr() . "\n\n" . $sql;
}

1;